package engine.systems.ui.dial
{
	import engine.classes.enumerations.SystemPriority;
	import engine.groups.Group;
	import engine.systems.update.GameSystem;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.text.TextField;
	
	
	public class DialSystem extends GameSystem
	{
		public function DialSystem()
		{
			super(DialNode, updateNode, nodeAdded);
			
			this.priority = SystemPriority.UPDATE;
		}
		
		private function updateNode(node:DialNode, time:Number):void
		{
			if(node.dial.invalidate)
			{
				var delta:Number = node.dial.distance * node.dial.rate * time;
				
				/**
				 * Broken.
				 */
				
				var container:DisplayObjectContainer = node.render.display as DisplayObjectContainer;
				var numVisible:int = (node.dial.numVisible - 1) / 2 + 1;
				
				if(node.dial.forward)
				{
					for(var i:int = 0; i <= node.dial.numVisible; i++)
					{
						var text:TextField = container.getChildByName(node.dial.prefix + i) as TextField;
						text.y -= delta;
						
						if(text.y <= -numVisible * node.dial.offset)
						{
							//node.dial.oldIndex += numVisible;
							trace(node.dial.oldIndex);
							if(++node.dial.oldIndex >= node.dial.values.length)
								node.dial.oldIndex -= node.dial.values.length;
							
							var next:int = node.dial.oldIndex + numVisible;
							if(next >= node.dial.values.length)
								next -= node.dial.values.length;
							
							text.text = node.dial.values[next];
							text.y += numVisible * 2 * node.dial.offset;
						}
					}
				}
				
				if(Math.abs(delta) < 0.1)
				{
					node.dial.invalidate = false;
					return;
				}
				
				node.dial.distance -= node.dial.distance * node.dial.rate * time;
			}
		}
		
		private function nodeAdded(node:DialNode):void
		{
			var container:DisplayObjectContainer = node.render.display as DisplayObjectContainer;
			var index:int = node.dial.index;
			
			var numVisible:int = (node.dial.numVisible - 1) / 2;
			
			index -= numVisible;
			if(index < 0) index += node.dial.values.length;
			
			for(var i:int = 0; i <= node.dial.numVisible; i++)
			{
				var text:TextField = container.getChildByName(node.dial.prefix + i) as TextField;
				text.x = 0;
				text.y = (i - numVisible) * node.dial.offset;
				
				var value:* = node.dial.values[index];
				text.text = value;
				
				if(++index >= node.dial.values.length) index = 0;
			}
		}
	}
}